
'use strict'

const fs = require('fs')
const path = require('path')

function inject(reg, root, target, replacement, default_val){

    return fs.readFileSync(path.join(root, target), 'utf8').replace(reg, (_, key)=>{
        key = key.replace(/\s+/g, '')
        if(fs.existsSync(path.join(root, key))){
            return inject(reg, root, key, replacement)
        }else if(key in replacement){
            return replacement[key]
        }else{
            return default_val(key)
        }
    })
}

function inject_html(root, target, output){
    let html = inject(/\<\s*include\s+src\s*\=\s*\"(.+?)\"\s*\/\s*\>/ig, root, target, {}, key=>`<h2>${key}未找到</h2>`)
    fs.writeFileSync(path.join(root, output), html)
}

function inject_js(root, target, output){

    // 加载所有boy, 并注入到入口页面
    let boy_list = []
    walk(root, './src/boy').forEach(filename => {
        if(/\.boy\.js$/i.test(filename)){
            let filename_r = path.relative(root, filename)
            let boyname = filename_r.replace(/^src[\/\\]+boy[\/\\]+/i, '').replace(/\.boy\.js$/i, '').split(/[\/\\]/).join('.')
            boy_list.push(`boy.setCurrentModelName('${boyname}')`)
            boy_list.push(`require('./${filename_r.replace(/^[\\\/]*src[\\//]*/i, '').replace(/[\\\/]/g, '/')}')(boy, '${boyname}')`)
        }
    })

    // 加载所有style, 并注入到入口页面
    let style_list = []
    walk(root, './src/style').forEach(filename => {
        if(/\.(less)|(sass)|(css)$/i.test(filename)){
            let filename_r = path.relative(root, filename)
            style_list.push(`import './${filename_r.replace(/^[\\\/]*src[\\//]*/i, '').replace(/[\\\/]/g, '/')}'`)
        }
    })

    // 加载所有test, 按需注入到入口页面
    let test_list = []
    walk(root, './src/test').forEach(filename => {
        if(/\.js$/.test(filename)){
            let filename_r = path.relative(root, filename)
            boy_list.push(`require('./${filename_r.replace(/^[\\\/]*src[\\//]*/i, '').replace(/[\\\/]/g, '/')}')(boy)`)
        }
    })

    let js = inject(/^\s*\/\/\s*include\s+(.+)/igm, root, target, {
        add_boys : boy_list.join('\n'),
        add_styles:style_list.join('\n'),
        add_test : test_list.join('\n'),
    }, key=>`alert('${key}未找到')`)
    fs.writeFileSync(path.join(root, output), js)
}

function walk(root, target){
    let res = []
    function inner(p){
        fs.readdirSync(p).forEach(filename=>{
            let filename_w = path.join(p, filename)
            if(fs.statSync(filename_w).isDirectory()){
                inner(filename_w)
            }else{
                res.push(filename_w)
            }
        })
    }
    inner(path.join(root, target))
    return res
}


module.exports = {inject_html, inject_js}